package com.zimmur.service.impl.account;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zimmur.dao.account.IUserNewMessageDao;
import com.zimmur.model.account.UserNewMessage;
import com.zimmur.service.account.IUserNewMessageService;
import com.zimmur.tools.DateUtils;
@Service("userNewMessageService")
public class UserNewMessageServiceImpl implements IUserNewMessageService{
	private static Logger log = LoggerFactory.getLogger(UserNewMessageServiceImpl.class);
	@Resource
	private IUserNewMessageDao userNewMessageDao;
	
	private static Object syncLock = new Object();
	
	@Override
	public int updateOrInsert(UserNewMessage userNewMessage) {
		int flag=0;
		synchronized (syncLock) {
			try {
				UserNewMessage exist=userNewMessageDao.selectMessageByKey(userNewMessage.getUserId(), userNewMessage.getCategoryCode());
				if(exist!=null){
					userNewMessage.setNumber(exist.getNumber()+1);
					flag=userNewMessageDao.updateMessage(userNewMessage);
					
				}else{
					userNewMessage.setNumber(1);
					flag=userNewMessageDao.insertMessage(userNewMessage);
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
		return flag;
	}

	@Override
	public Map<String,	UserNewMessage> selectMessageByUserId(Long userId) {
		List<UserNewMessage> userNewMessages=userNewMessageDao.selectMessageByUserId(userId);
		
		Map<String,	UserNewMessage> map=new HashMap<>();
		if (userNewMessages ==null || userNewMessages.size() != 3) {
			
			UserNewMessage userNewMessage=new UserNewMessage();
			int nowUnixTime=DateUtils.getNowUnixTime();
			userNewMessage.setContent("暂无更多消息！");
			userNewMessage.setUpdateDate(nowUnixTime);
			userNewMessage.setMsgDate("");
			userNewMessage.setNumber(0);
			userNewMessage.setUserId(userId);
			map.put("notify", userNewMessage);
			map.put("organization", userNewMessage);
			map.put("service", userNewMessage);
		}
		
		for(UserNewMessage message:userNewMessages ){
			message.setMsgDate(DateUtils.getUnixTimeToDefineFormat(message.getUpdateDate()));
			map.put(message.getCategoryCode(), message);
		}
		
		return map;
	}

	@Override
	public int updateNumber(Long userId, String categoryCode) {
		UserNewMessage exist=userNewMessageDao.selectMessageByKey(userId, categoryCode);
		int flag=0;
		if (exist!=null) {
			exist.setNumber(0);
			flag=userNewMessageDao.updateMessage(exist);
		}
		return flag;
	}

	@Override
	public int selectNoReadMessageNum(long userId) {
		Integer num=userNewMessageDao.selectNoReadNum(userId);
		if(num==null)
			num=0;
		
		return num;
	}

}
